$.validator.setDefaults({
	highlight: function (element) {
		$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
    },success: function (element) {
    	element.closest('.form-group').removeClass('has-error').addClass('has-success');
    },errorElement: "span",
    errorPlacement: function (error, element) {
        if (element.is(":radio") || element.is(":checkbox")) {
            error.appendTo(element.parent().parent().parent());
        } else {
            error.appendTo(element.parent());
        }
    },errorClass: "help-block m-b-none",
    validClass: "help-block m-b-none"
});
var branch = function(){
	/**
	 * 初始化栏目表格
	 */
	var handleTable = function(){
		var ctable = $('.branchTable');
		var ccTable = ctable.dataTable({
	        "lengthMenu": [
	               [10,20,30,40,50,100],
	               [10,20,30,40,50,100]
	        ],
	        "pageLength": 10,
	        "language": {
	        	"processing": "数据加载中...",
	            "emptyTable": "暂无数据",
	            "info": "第_START_到_END_条记录,共_TOTAL_条记录",
	            "infoEmpty": "没有找到记录",
	            "infoFiltered": "",
	            "lengthMenu": "每页显示 _MENU_ 条记录",
	            "search": "搜索:",
	            "zeroRecords": "未找到匹配记录",
	            "paginate": {
	                "previous":"上一页",
	                "next": "下一页",
	                "last": "末页",
	                "first": "首页"
	            }
	        },
	        "columnDefs": [
	            {'orderable': false,"data":"id",'targets': [0],'Sortable': false,"visible": false},
	            {'orderable': false,"data":"secret",'targets': [1],'Sortable': false,"visible": false},
	            {'orderable': false,"data":"name",'targets': [2],'Sortable': false,"title":"平台名称",
	            	"render":function(data, type, full){
	                	if(full.name===""){
	                		return"<span style='color:red;'>无</span>";
	                    }else{
	                    	return full.name;
	                    }
	                }
	            },
	            {'orderable': false,"data":"createTime",'targets': [3],"title":"创建时间",
	                "render":function(data, type, full){
	                	if(full.createTime===""){
	                		return"<span style='color:red;'>无</span>";
	                    }else{
	                    	return full.createTime;
	                    }
	                }
	            },{'orderable': false,"data":"username",'targets': [4],"title":"创建人",
	                "render":function(data, type, full){
	                	if(full.username===""){
	                		return"<span style='color:red;'>无</span>";
	                    }else{
	                    	return full.username;
	                    }
	                }
	            },{'orderable': false,"data":"startTime",'targets': [5],"title":"记录获取开始时间",
	                "render":function(data, type, full){
	                	if(full.startTime===""||full.startTime===undefined){
	                		return"<span style='color:red;'>无</span>";
	                    }else{
	                    	return full.startTime;
	                    }
	                }
	            },{'orderable': false,"data":"status",'targets': [6],"title":"状态",
	                "render":function(data, type, full){
	                	if(full.status==0){
	                		return"<span class='label label-primary'>可用</span>";
	                    }else if(full.status==1){
	                    	return"<span class='label label-danger'>暂停使用</span>";
	                    }else if(full.status==2){
	                    	return"<span class='label label-info'>待审核</span>";
	                    }else if(full.status==3){
	                    	return"<span class='label label-warning'>未通过</span>";
	                    } 
	                }
	            },
	           {'orderable': false,'targets': [7],"title":"操作",
	          	 "render":function(data,type,full){
	          		 // -1、删除  0、可用  1、禁用 2、审核中 3、审核不通过  
	          		 var btn = "";
	          		 if(full.status!=2&&full.status!=3){
//	          			btn +="&nbsp;<button class='btn btn-success' type='button' id='resetBtn'><i class='fa fa-refresh'></i> 重置安全码</button>";
	          		 }
	          		 if(full.status==0){
	          			 btn +="&nbsp;<button class='btn btn-primary' type='button' id='secretBtn'><i class='fa fa-search'></i> 查看安全码</button>";
	          			 btn +="&nbsp;<button class='btn btn-warning' type='button' id='banBtn'><i class='fa fa-ban'></i> 暂停使用</button>";
	          		 }else if(full.status==1){
	          			btn +="&nbsp;<button class='btn btn-primary' type='button' id='secretBtn'><i class='fa fa-search'></i> 查看安全码</button>";
	          			btn +="&nbsp;<button class='btn btn-info' type='button' id='recoveryBtn'><i class='fa fa-check'></i> 恢复使用</button>";
	          		 }else if(full.status==2){
//	          			btn +="&nbsp;<button class='btn btn-info' type='button' id='recoveryBtn'><i class='fa fa-check'></i> 恢复</button>";
	          		 }else if(full.status==3){
	          			btn +="&nbsp;<button class='btn btn-info' type='button' id='reloadBtn'><i class='fa fa-refresh'></i> 重新审核</button>";
	          		 } 
	          		 btn +="&nbsp;<button class='btn btn-danger' type='button' id='delBtn'><i class='fa fa-remove'></i> 删除</button>";
	          		 return btn;
	          	 }
	           },
	        ],
	        "bAutoWidth":false,
	        "bProcessing": true, // 是否显示取数据时的那个等待提示
		    "bServerSide": true,//这个用来指明是通过服务端来取数据
	        "sAjaxSource":"../../admin/branch/get",//请求的地址
	        "fnServerData": function(sSource,aoData,fnCallback){				  // 获取数据的处理函数
	        	$.ajax({
	        		url:sSource,
	        		type : "post",
	        		data:{
	        			"aoData":JSON.stringify(aoData)
	        		},
	        		dataType : "json",
	        		async:false,
	        		success:function(result){
	        			if(result.success){
	        				fnCallback(result.obj);
	        				
	        			}else{
	        			}
	        		},error:function(msg){
	        			if(a.readyState==4){
		    				window.location.href="../admin/loginpage";
		    			}else{
		    				toastr.error("系统异常！");
		    			}
	        		}
	        	});
	        } 
	    });
		
		ctable.on( 'draw.dt', function () {
			ccTable.$('tr').find("td:first").editable('../../admin/branch/edit', {
	             callback: function (result, y) {
	            	 result= eval("("+result+")");
	            	 if(result.success){
	            		 var aPos = ccTable.fnGetPosition(this);
	            		 ccTable.fnUpdate(result.obj, aPos[0],2,false);  
	            		 toastr.success("修改成功！");
	            	 }else{
	            		 toastr.error("修改失败！");
	            	 }
	             },tooltip: '点击编辑...',
	             indicator: '保存中...',
	             submitdata: function (value, settings) {
	            	 var nRow = $(this).parents('tr');
	     	    	 var dData = ccTable.fnGetData(nRow);
		             return {"id": dData.id};
	             },onsubmit : function(settings, original){
	            	 $(this).validate({
	            		 errorPlacement: function(error, element) {
	                         var form = $(element).parent();
	                         form.next().remove();
	                         form.parent().append(error);
	                     },
	                     success: function(error, element) {
	                         var form = $(element).parent();
	                         form.next().remove();
	                     },rules: {
	                     	value:{
	                     		required:true,
	         	        		minlength:2,
	         	        		remote:{
	         	        			type:"post",
	         	        			url:"../../admin/check/branchname",
	         	        			async:false,
	         	        			data:{
	         	        				"name":function(){return  $(original).find('input').val();}
	         	        			},dataFilter: function (data) {
	         	                 		data=eval("("+data+")");
	         	                 		return data.success;
	         	                 	}
	         	        		}
	                         }
	                     },messages: {
	                         value:{
	         	               	required:"平台不能为空",
	         		        	minlength:"平台长度不能小于2",
	         		        	remote: "平台已存在"
	                         }
	                     } 
	            	 });
	                 return $(this).valid();
	             },
	             width :"50%",
	             height:"100%",
	             cancel:'取消', 
	             submit:'确定', 
	             onblur:"ignore"
	         });
			$.editable.addInputType('starttime', {
			    element : function(settings, original) {
			    	var input = $("<input id='startTime'readonly  name='startTime' class='form-control layer-date laydate-icon' placeholder='YYYY-MM-DD hh:mm:ss'>");
			        input.on("click",function(e){
			        	 laydate({
			        		 istime: true,
			        		 format: 'YYYY-MM-DD hh:mm:ss',
			                 elem: '#startTime', //目标元素。由于laydate.js封装了一个轻量级的选择器引擎，因此elem还允许你传入class、tag但必须按照这种方式 '#id .class'
			                 event: 'focus' //响应事件。如果没有传入event，则按照默认的click
			             });
			        });
			    	$(this).append(input);
			        return(input);
			    }
			});
			
			
			ccTable.$('tr').find("td:eq(3)").editable('../../admin/branch/edits',{
		            callback: function (result, y) {
			           	 result= eval("("+result+")");
			           	 if(result.success){
			           		 var aPos = ccTable.fnGetPosition(this);
			           		 ccTable.fnUpdate(result.obj,aPos[0],5,false);  
			           		 toastr.success("修改成功！");
			           	 }else{
			           		 toastr.error("修改失败！");
			           	 }
		            },tooltip: '点击编辑...',
		            indicator: '保存中...',
		            submitdata: function (value, settings) {
		           	 	var nRow = $(this).parents('tr');
		    	    	 var dData = ccTable.fnGetData(nRow);
			             return {"id": dData.id};
		            },
		            width :"50%",
		            height:"100%",
		            cancel:'取消', 
		            submit:'确定',
		            type:"starttime",
		            data:function(){
		            	var nRow = $(this).parents('tr');
		    	    	var dData = ccTable.fnGetData(nRow);
		    	    	if(dData.startTime===""||dData.startTime===undefined){
	                		return "";
	                    }else{
	                    	return dData.startTime;
	                    }
		            },onblur:"ignore"
			});
		});
		
		
		//查看安全码
		ctable.on("click","#secretBtn",function(e){
			e.preventDefault();	
	    	var nRow = $(this).parents('tr');
	    	var dData = ccTable.fnGetData(nRow);
	    	swal("您的安全码是", dData.secret);
		});
		//重置安全码
		ctable.on("click","#resetBtn",function(e){
			e.preventDefault();	
	    	var nRow = $(this).parents('tr');
	    	var dData = ccTable.fnGetData(nRow);
	    	$.ajax({
	    		url:"../../admin/branch/reset",
				type:"post",
				dataType:"json",
				data:{"id":dData.id},
				success : function(data){
					if(data.success){
						swal({
							 title: "安全码重置成功",  
	                         text: "您的安全码是："+data.obj,  
	                         type: "success",  
						});
								
						ctable.fnDraw(true);
					}else{
						toastr.success("删除失败！");
					}
				},error:function(a,b,c){
					if(a.readyState==4){
	    				window.location.href="../../admin/loginpage";
	    			}else{
	    				toastr.error("系统异常！");
	    			}
				}
	    	});
		});
		//删除平台
		ctable.on("click","#delBtn",function(e){
			e.preventDefault();	
	    	var nRow = $(this).parents('tr');
	    	var dData = ccTable.fnGetData(nRow);
	    	$.ajax({
	    		url:"../../admin/branch/del",
				type:"get",
				dataType:"json",
				data:{"id":dData.id},
				success : function(data){
					if(data.success){
						toastr.success("删除成功！");
						ctable.fnDraw(true);
					}else{
						toastr.success("删除失败！");
					}
				},error:function(){
					if(a.readyState==4){
	    				window.location.href="../../admin/loginpage";
	    			}else{
	    				toastr.error("系统异常！");
	    			}
				}
	    	});
		});
		
		//停用平台
		ctable.on("click","#banBtn",function(e){
			e.preventDefault();	
	    	var nRow = $(this).parents('tr');
	    	var dData = ccTable.fnGetData(nRow);
	    	$.ajax({
	    		url:"../../admin/branch/ban",
				type:"POST",
				dataType:"json",
				data:{"id":dData.id},
				success : function(data){
					if(data.success){
						toastr.success("停用成功！");
						ctable.fnDraw(true);
					}else{
						toastr.success("停用失败！");
					}
				},error:function(a,b,c){
					if(a.readyState==4){
	    				window.location.href="../../admin/loginpage";
	    			}else{
	    				toastr.error("系统异常！");
	    			}
				}
	    	});
	    	
		});
		
		//重新审核
		ctable.on("click","#reloadBtn",function(e){
			e.preventDefault();	
	    	var nRow = $(this).parents('tr');
	    	var dData = ccTable.fnGetData(nRow);
	    	$.ajax({
	    		url:"../../admin/branch/reload",
				type:"POST",
				dataType:"json",
				data:{"id":dData.id},
				success : function(data){
					if(data.success){
						toastr.success("提交审核成功！");
						ctable.fnDraw(true);
					}else{
						toastr.success("提交审核失败！");
					}
				},error:function(a,b,c){
					if(a.readyState==4){
	    				window.location.href="../../admin/loginpage";
	    			}else{
	    				toastr.error("系统异常！");
	    			}
				}
	    	});
	    	
		});
		//恢复平台
		ctable.on("click","#recoveryBtn",function(e){
			e.preventDefault();	
	    	var nRow = $(this).parents('tr');
	    	var dData = ccTable.fnGetData(nRow);
	    	$.ajax({
	    		url:"../../admin/branch/recovery",
				type:"POST",
				dataType:"json",
				data:{"id":dData.id},
				success : function(data){
					if(data.success){
						toastr.success("恢复成功！");
						ctable.fnDraw(true);
					}else{
						toastr.success("恢复失败！");
					}
				},error:function(a,b,c){
					if(a.readyState==4){
	    				window.location.href="../../admin/loginpage";
	    			}else{
	    				toastr.error("系统异常！");
	    			}
				}
	    	});
		});
		
		ccTable.$('tr').find("td:first").editable('../../admin/branch/edit', {
             callback: function (result, y) {
            	 result= eval("("+result+")");
            	 if(result.success){
            		 var aPos = ccTable.fnGetPosition(this);
            		 ccTable.fnUpdate(result.obj, aPos[0],2,false);  
            		 toastr.success("修改成功！");
            	 }else{
            		 toastr.error("修改失败！");
            	 }
             },tooltip: '点击编辑...',
             indicator: '保存中...',
             submitdata: function (value, settings) {
            	 var nRow = $(this).parents('tr');
     	    	 var dData = ccTable.fnGetData(nRow);
	             return {"id": dData.id};
             },onsubmit : function(settings, original){
            	 $(this).validate({
            		 errorPlacement: function(error, element) {
                         var form = $(element).parent();
                         form.next().remove();
                         form.parent().append(error);
                     },
                     success: function(error, element) {
                         var form = $(element).parent();
                         form.next().remove();
                     },rules: {
                     	value:{
                     		required:true,
         	        		minlength:2,
         	        		remote:{
         	        			type:"post",
         	        			url:"../../admin/check/branchname",
         	        			async:false,
         	        			data:{
         	        				"name":function(){return  $(original).find('input').val();}
         	        			},dataFilter: function (data) {
         	                 		data=eval("("+data+")");
         	                 		return data.success;
         	                 	}
         	        		}
                         }
                     },messages: {
                         value:{
         	               	required:"平台不能为空",
         		        	minlength:"平台长度不能小于2",
         		        	remote: "平台已存在"
                         }
                     } 
            	 });
                 return $(this).valid();
             },
             width :"50%",
             height:"100%",
             cancel:'取消', 
             submit:'确定', 
             onblur:"ignore"
         });
	
		
		$.editable.addInputType('starttime', {
		    element : function(settings, original) {
		    	var input = $("<input id='startTime'readonly  name='startTime' class='form-control layer-date laydate-icon' placeholder='YYYY-MM-DD hh:mm:ss'>");
		        input.on("click",function(e){
		        	 laydate({
		        		 istime: true,
		        		 format: 'YYYY-MM-DD hh:mm:ss',
		                 elem: '#startTime', //目标元素。由于laydate.js封装了一个轻量级的选择器引擎，因此elem还允许你传入class、tag但必须按照这种方式 '#id .class'
		                 event: 'focus' //响应事件。如果没有传入event，则按照默认的click
		             });
		        });
		    	$(this).append(input);
		        return(input);
		    }
		});
		
		
		ccTable.$('tr').find("td:eq(3)").editable('../../admin/branch/edits',{
	            callback: function (result, y) {
		           	 result= eval("("+result+")");
		           	 if(result.success){
		           		 var aPos = ccTable.fnGetPosition(this);
		           		 ccTable.fnUpdate(result.obj,aPos[0],5,false);  
		           		 toastr.success("修改成功！");
		           	 }else{
		           		 toastr.error("修改失败！");
		           	 }
	            },tooltip: '点击编辑...',
	            indicator: '保存中...',
	            submitdata: function (value, settings) {
	           	 	var nRow = $(this).parents('tr');
	    	    	 var dData = ccTable.fnGetData(nRow);
		             return {"id": dData.id};
	            },
	            width :"50%",
	            height:"100%",
	            cancel:'取消', 
	            submit:'确定',
	            type:"starttime",
	            data:function(){
	            	var nRow = $(this).parents('tr');
	    	    	var dData = ccTable.fnGetData(nRow);
	    	    	if(dData.startTime===""||dData.startTime===undefined){
                		return "";
                    }else{
                    	return dData.startTime;
                    }
	            },onblur:"ignore"
	            
		});
		
		
		
		/**
		 * 添加框
		 */
		$("#addBranchBtn").on("click",function(){
			$("#addBranchModal").modal();
		});
	};
	
	var handleValidate = function(){
		jQuery.validator.addMethod("isMobile", function(value, element) {
		    var length = value.length;
		    var mobile = /^(13[0-9]{9})|(18[0-9]{9})|(14[0-9]{9})|(17[0-9]{9})|(15[0-9]{9})$/;
		    return this.optional(element) || (length == 11 && mobile.test(value));
		}, "请正确填写您的手机号码");
		var icon = "<i class='fa fa-times-circle'></i> ";
		$("#addBranchForm").validate({
			onfocusout: function(element) { $(element).valid();},
			errorPlacement: function (error, element) {
				if (element.is(":radio") || element.is(":checkbox")) {
		            error.appendTo(element.parent().parent().parent());
		        }else if (element.is("#checkNum")) {
		            error.appendTo(element.parent().parent());
		        } 
				else {
		            error.appendTo(element.parent());
		        }
		    },
	        rules: {
	        	name: {
	        		required:true,
	        		minlength:2,
	        		remote:{
	        			type:"post",
	        			url:"../../admin/check/branchname",
	        			data:{
	        				"name":function(){return  $("#name").val();}
	        			},dataFilter: function (data) {
	                 		data=eval("("+data+")");
	                 		return data.success;
	                 	}
	        		}
	        	},userphone: {
	        		required:true,
	        		isMobile:true,
	        		minlength:11
	        	},checkNum: {
	        		 digits : true,
	                 required : true,
	                 remote:{
	         			type:"get",
	                 	url:"../../admin/check/code",
	                 	data : {
	                 		"phone": function() {return $("#userphone").val();},
	                 		"code": function() {return $("#checkNum").val();}
	                 	},dataFilter: function (data) {
	                 		data=eval("("+data+")");
	                 		return data.success;
	                 	}
	         		}
	        	}
	        },
	        messages: {
	        	name: {
	        		required:icon +"平台不能为空",
	        		minlength:icon +"平台长度不能小于2",
	        		remote:icon + "平台已存在"
	        	},userphone: {
	        		required:icon + "用户手机号不能为空",
	        		isMobile:icon + "请输入正确的手机号",
	        		minlength:icon + "手机号长度不正确"
	        	},checkNum: {
	        		 digits : icon + "验证码只能为数字",
	                 required : icon + "验证码不能为空",
	                 remote:icon+"验证码不正确"
	        	}
	        }
	    });
	};
	$("#checkNumBtn").on("click",function(){
		if($("#addBranchForm").validate().element($("#userphone"))){
			$.ajax({
				url:"../../sms/send",
				type:"get",
				dataType:"json",
				data:{phone:$("#userphone").val()},
				success : function(data){
					if(data.success){
						var time = 90;
						setInterval(function(){
			                if(time<=0){
			                	$("#checkNumBtn").html("重新获取").removeAttr("disabled").css("color","")
			                    return;
			                }
			                time--;
			                $("#checkNumBtn").html("重新获取("+time+")").attr("disabled","disabled").css("color","#fff");
			            },1000);
						
					}else{
						
					}
				},error:function(a,b,c){
					swal({
                        title: "获取失败",
                        text: "系统异常！请稍后再试",
                        type: "error"
                    });
				}
			});
		}
	});
	$("#addBranchSubmit").on("click",function(){
		if($("#addBranchForm").validate().form()){
			$.ajax({
				url :"../../admin/branch/add",
				type : "post",
				dataType:"json",
				data : $('#addBranchForm').serialize(),
				success : function(data){
					if(data.success){
						swal({
					        title: "申请成功",
					        type: "success",
					        text:"您的安全码是:"+data.obj.secret+" 待管理员审核通过后可用"
					    });
						$("#addBranchModal").modal('hide');
						$('.branchTable').dataTable().fnDraw(true);
					}else{
						swal({
	                        title: "注册失败",
	                        text: "系统异常！请稍后再试",
	                        type: "warning"
	                    });
					}
				},error:function(a,b,c){
					swal({
                        title: "注册失败",
                        text: "系统异常！请稍后再试",
                        type: "warning"
                    });
				}
			});
		}
	});
	
	
	return {
		init : function(){
			handleTable();
			handleValidate();
		} 
	};
}();
branch.init();
